package com.ruoyi.bantong.service.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.bantong.constant.BanTongConstants;
import com.ruoyi.bantong.domain.BtOrganization;
import com.ruoyi.bantong.domain.BtOrganizationAccountRecord;
import com.ruoyi.bantong.mapper.BtOrganizationAccountRecordMapper;
import com.ruoyi.bantong.mapper.BtOrganizationMapper;
import com.ruoyi.bantong.mapper.BtUserMapper;
import com.ruoyi.common.core.domain.entity.BtUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.bantong.mapper.BtUserAccountRecordMapper;
import com.ruoyi.bantong.domain.BtUserAccountRecord;
import com.ruoyi.bantong.service.IBtUserAccountRecordService;

/**
 * 用户账户变动记录Service业务层处理
 * 
 * @author laohei
 * @date 2021-01-24
 */
@Service
public class BtUserAccountRecordServiceImpl implements IBtUserAccountRecordService 
{
    @Autowired
    private BtUserAccountRecordMapper btUserAccountRecordMapper;
    @Autowired
    private BtUserMapper btUserMapper;

    @Autowired
    private BtOrganizationMapper organizationMapper;

    @Autowired
    private BtOrganizationAccountRecordMapper organizationAccountRecordMapper;

    /**
     * 查询用户账户变动记录
     * 
     * @param usrId 用户账户变动记录ID
     * @return 用户账户变动记录
     */
    @Override
    public BtUserAccountRecord selectBtUserAccountRecordById(Integer usrId)
    {
        return btUserAccountRecordMapper.selectBtUserAccountRecordById(usrId);
    }

    /**
     * 查询用户账户变动记录列表
     * 
     * @param btUserAccountRecord 用户账户变动记录
     * @return 用户账户变动记录
     */
    @Override
    public List<BtUserAccountRecord> selectBtUserAccountRecordList(BtUserAccountRecord btUserAccountRecord)
    {
        return btUserAccountRecordMapper.selectBtUserAccountRecordList(btUserAccountRecord);
    }

    /**
     * 新增用户账户变动记录
     * 
     * @param btUserAccountRecord 用户账户变动记录
     * @return 结果
     */
    @Override
    public int insertBtUserAccountRecord(BtUserAccountRecord btUserAccountRecord)
    {
        btUserAccountRecord.setCreateTime(DateUtils.getNowDate());
        return btUserAccountRecordMapper.insertBtUserAccountRecord(btUserAccountRecord);
    }

    /**
     * 修改用户账户变动记录
     * 
     * @param btUserAccountRecord 用户账户变动记录
     * @return 结果
     */
    @Override
    public int updateBtUserAccountRecord(BtUserAccountRecord btUserAccountRecord)
    {
        btUserAccountRecord.setUpdateTime(DateUtils.getNowDate());
        return btUserAccountRecordMapper.updateBtUserAccountRecord(btUserAccountRecord);
    }

    /**
     * 批量删除用户账户变动记录
     * 
     * @param usrIds 需要删除的用户账户变动记录ID
     * @return 结果
     */
    @Override
    public int deleteBtUserAccountRecordByIds(Integer[] usrIds)
    {
        return btUserAccountRecordMapper.deleteBtUserAccountRecordByIds(usrIds);
    }

    /**
     * 删除用户账户变动记录信息
     * 
     * @param usrId 用户账户变动记录ID
     * @return 结果
     */
    @Override
    public int deleteBtUserAccountRecordById(Integer usrId)
    {
        return btUserAccountRecordMapper.deleteBtUserAccountRecordById(usrId);
    }

    //构建余额变动记录
    public void updataUserAccount(Integer btUserId, BigDecimal bean, BigDecimal score,
                                  Integer id,String table,String changeType,
                                   Integer actionType) {
        try {
            BtUser btUser = btUserMapper.selectBtUserById(btUserId);

            BtUserAccountRecord accountRecord = new BtUserAccountRecord();
            accountRecord.setUserId(btUser.getUserId());
            accountRecord.setBefBeanBalance(btUser.getBtBean());
            accountRecord.setBefScoreBalance(btUser.getBtScore());
            accountRecord.setBean(bean);
            accountRecord.setScore(score);
            BigDecimal BigBtBean = btUser.getBtBean();
            BigDecimal Bigbean = bean;
            BigDecimal BigBtBeanBalance = BigDecimal.ZERO;

            BigDecimal BigScore = score;
            BigDecimal BigBtScore = btUser.getBtScore();
            BigDecimal BigBtScoreBalance = BigDecimal.ZERO;
            if("in".equals(changeType)){
                BigBtBeanBalance = BigBtBean.add(Bigbean);
                BigBtScoreBalance = BigBtScore.add(BigScore);

            }else {
                BigBtBeanBalance = BigBtBean.subtract(Bigbean);
                BigBtScoreBalance = BigBtScore.subtract(BigScore);
            }
            accountRecord.setBeanBalance(BigBtBeanBalance);
            accountRecord.setScoreBalance(BigBtScoreBalance);
            accountRecord.setActionType((Integer)getFinalFieldValueByName("ACCOUNT_ACTION_TYPE" + actionType, BanTongConstants.class));//参加席位玩法  扣除保证金
            accountRecord.setMemo((String)getFinalFieldValueByName("ACCOUNT_MEMO_TYPE" + actionType, BanTongConstants.class));
            accountRecord.setChangeType(changeType);
            accountRecord.setCorrelationId(id);
            accountRecord.setCorrelationTable(table);
            accountRecord.setCreateTime(DateUtils.getNowDate());
            String createBy = StringUtils.isNull(SecurityUtils.getBtUserId()) ? SecurityUtils.getUsername() : SecurityUtils.getBtUserId().toString();
            accountRecord.setCreateBy(StringUtils.isEmpty(createBy) ? null : createBy);
            btUserAccountRecordMapper.insertBtUserAccountRecord(accountRecord);

            //用户账户变动
            BtUser btUser1 = new BtUser();
            btUser1.setUserId(btUser.getUserId());
            btUser1.setBtBean(BigBtBeanBalance);
            btUser1.setBtScore(BigBtScoreBalance);
            btUser1.setUpdateTime(DateUtils.getNowDate());
            btUserMapper.updateBtUser(btUser1);
            updataOrganizationAccount(btUserId,bean,score,id,table,changeType,actionType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //构建机构余额变动记录
    public void updataOrganizationAccount(Integer btUserId, BigDecimal bean, BigDecimal score,
                                          Integer id,String table,String changeType,
                                          Integer actionType) throws Exception{
        BtUser btUser = btUserMapper.selectBtUserById(btUserId);
        Integer orgId = btUser.getOrgId(); //机构ID
        BtOrganization btOrganization = organizationMapper.selectBtOrganizationById(orgId);

        BtOrganizationAccountRecord accountRecord = new BtOrganizationAccountRecord();
        accountRecord.setOrgId(orgId);
        accountRecord.setUserId(btUser.getUserId());
        accountRecord.setBefBeanBalance(btOrganization.getBtBean());
        accountRecord.setBefScoreBalance(btOrganization.getBtScore());
        accountRecord.setBean(bean);
        accountRecord.setScore(score);
        BigDecimal BigBtBean = btOrganization.getBtBean();
        BigDecimal Bigbean = bean;
        BigDecimal BigBtBeanBalance = BigDecimal.ZERO;

        BigDecimal BigScore = score;
        BigDecimal BigBtScore = btOrganization.getBtScore();
        BigDecimal BigBtScoreBalance ;
        if("in".equals(changeType)){
            BigBtBeanBalance = BigBtBean.add(Bigbean);
            BigBtScoreBalance = BigBtScore.add(BigScore);

        }else {
            BigBtBeanBalance = BigBtBean.subtract(Bigbean);
            BigBtScoreBalance = BigBtScore.subtract(BigScore);
        }
        accountRecord.setBeanBalance(BigBtBeanBalance);
        accountRecord.setScoreBalance(BigBtScoreBalance);
        accountRecord.setActionType((Integer)getFinalFieldValueByName("ACCOUNT_ACTION_TYPE" + actionType, BanTongConstants.class));//参加席位玩法  扣除保证金
        accountRecord.setMemo((String)getFinalFieldValueByName("ACCOUNT_MEMO_TYPE" + actionType, BanTongConstants.class));
        accountRecord.setChangeType(changeType);
        accountRecord.setCorrelationId(id);
        accountRecord.setCorrelationTable(table);
        accountRecord.setCreateTime(DateUtils.getNowDate());
        String createBy = StringUtils.isNull(SecurityUtils.getBtUserId()) ? SecurityUtils.getUsername() : SecurityUtils.getBtUserId().toString();
        accountRecord.setCreateBy(StringUtils.isEmpty(createBy) ? null : createBy);
        organizationAccountRecordMapper.insertBtOrganizationAccountRecord(accountRecord);

        //用户账户变动
        BtOrganization Organization1 = new BtOrganization();
        Organization1.setOrgId(orgId);
        Organization1.setBtBean(BigBtBeanBalance);
        Organization1.setBtScore(BigBtScoreBalance);
        Organization1.setUpdateTime(DateUtils.getNowDate());
        organizationMapper.updateBtOrganization(Organization1);
    }

    /**
     * 通过常量属性名字,在字节码中获取到一个常量的值
     * 这个方法常用于取出接口中常量的值,可以适用于接口中的常量;类中的常量,但是仅限于常量.如果是变量,返回为空
     * 注意: 如果你要取出来的不是常量,我也给你返回了null,这是为了确保,取出来的一定是 final 的常量
     * @param   fieldName  属性的名字
     * @param   clazz   在那个字节码中
     * @return  如果找找到,并且他也是常量,我就返回它的值,否则返回null
     * @throws Exception 反射的风险异常.
     */
    public static Object getFinalFieldValueByName(String fieldName, Class<?> clazz) throws Exception {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            //确保你要取的,是常量.否则,就不用进去这个获取操作了
            boolean isFinal = Modifier.isFinal(field.getModifiers());
            if(isFinal){
                String name = field.getName();
                if (fieldName.equals(name)) {
                    return field.get(null);
                }
            }
        }
        return null;
    }

    /**
     * 后台首页统计
     * 1.售出金豆（统计的是平台给所有机构充值的金豆总合）
     * 2.全部版通（统计的是会员中签后获得的版通总积分）
     * 3.未兑换版通（统计的是现在所有会员拥有的版通积分总数）
     * 4.已兑换版通（统计的是会员获得版通积分后，来平台兑换版通后扣除的总数）（3+4的总合应该等于2）
     */
    @Override
    public Map<String, Object> selectMainData() {
        Map<String, Object> map = btUserAccountRecordMapper.selectMainData();
        return map;
    }

    /**
     * 后台首页统计
     * 5.统计一下每天的销售情况，用列表显示，只显示前一天的情况，统计时间为每天0点截止 列表维度为：1.充值金豆数 2.兑换版通数。
     */
    @Override
    public List<Map<String, Object>> selectListOrderByDay() {
        return btUserAccountRecordMapper.selectListOrderByDay();
    }

    public static void main(String[] args) {
        String str = "ACCOUNT_MEMO_TYPE" + 1;
        try {
            Object finalFieldValueByName = getFinalFieldValueByName(str, BanTongConstants.class);
            System.out.println(finalFieldValueByName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
